package top.lingkang.finalgateway.core;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;
import top.lingkang.finalgateway.utils.HttpUtils;

/**
 * @author lingkang
 * Created by 2024/5/10
 */
@Slf4j
public class FinalHttpObjectAggregator extends HttpObjectAggregator {
    private static final FullHttpResponse TOO_LARGE_CLOSE = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, Unpooled.EMPTY_BUFFER);

    public FinalHttpObjectAggregator(int maxContentLength) {
        super(maxContentLength);
    }

    @Override
    protected void handleOversizedMessage(ChannelHandlerContext ctx, HttpMessage oversized) throws Exception {
        if (oversized instanceof HttpRequest) {
            log.warn("Failed to send a 413 Request Entity Too Large. url={}", ((HttpRequest) oversized).uri());
            HttpUtils.returnTooLarge(ctx, maxContentLength());
        } else if (oversized instanceof HttpResponse) {
            ctx.close();
            throw new TooLongHttpContentException("Response entity too large: " + oversized);
        } else {
            throw new IllegalStateException();
        }
    }
}
